const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require('@koa/cors')

const live = require('./routes/live.js')
const search = require('./routes/search.js')
const shop = require('./routes/shop.js')
const show = require('./routes/show.js')
const recommend = require('./routes/recommend.js')
const slideshow = require('./routes/slideshow.js')
const login = require('./routes/login.js')
const register = require('./routes/register.js')
const add = require('./routes/add.js')

app.use(cors())

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(live.routes(), live.allowedMethods())
app.use(shop.routes(), shop.allowedMethods())
app.use(show.routes(), show.allowedMethods())
app.use(recommend.routes(), recommend.allowedMethods())
app.use(search.routes(), search.allowedMethods())
app.use(slideshow.routes(), slideshow.allowedMethods())
app.use(login.routes(), login.allowedMethods())
app.use(register.routes(), register.allowedMethods())
app.use(add.routes(), add.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});
module.exports = app
